import React, { useState, useEffect, useImperativeHandle } from 'react';
import { Table, Form } from 'antd';
import { getMaterialModalColumns } from '../mconfig/MaterialModalColumns';
import { MaterialManageAPI } from '../common/type';
import { getKeyRouter, getTenantID } from '@/utils';
import '../common/styles.less';
import Cls from 'classnames';
import _ from 'lodash';
import { ILoadMapTypeAll } from '@/common';

export const UploadSecordStep = React.forwardRef<MaterialManageAPI.IUploadFormRef, MaterialManageAPI.ISecordStepUpload>(
  ({ prefix, current, tableList }, ref) => {
    /**updata表单的ref*/
    const [uploadForm] = Form.useForm();

    useImperativeHandle(ref, () => ({ secordStepForm: uploadForm }));

    // 物料表格数据
    const [dataSource, setDataSource] = useState<Record<string, any>[]>([]); //uploadForm?.getFieldValue('table')

    const setTableRowClassName = (_: Record<string, any>, index: number) => (index % 2 == 0 ? 'double-row' : 'default-row');

    /** 监听导入的数据  保存一份 */
    useEffect(() => {
      if (tableList && tableList?.length > 0) {
        let newTableList: any[] = [];
        tableList?.map((item, index) => {
          newTableList.push(
            Object.assign({}, item, {
              keyID: `${item.unitPrice}${index}${getKeyRouter()}${getKeyRouter()}${getKeyRouter()}`,
            }),
          );
        });
        setDataSource(newTableList);
      }
    }, [tableList]);

    /** 监听保存的导入数据  渲染table */
    useEffect(() => {
      if (dataSource?.length > 0) {
        let newdata = _?.cloneDeep(dataSource);
        newdata?.forEach((item) => (item.supplyType = `${getTenantID()}${ILoadMapTypeAll.PURCHASE_CATEGORY}1000`));
        uploadForm?.setFieldsValue({
          table: newdata?.length > 0 ? newdata : [],
        });
      }
    }, [dataSource]);

    return (
      <div className={Cls('list-table', 'MaterialModalTable', 'bathModalFormStyle')} style={{ display: current === 1 ? 'block' : 'none' }}>
        <Form form={uploadForm}>
          <Form.Item name="table" valuePropName="dataSource">
            <Table
              size="small"
              bordered
              scroll={{ x: 1200, y: 'true' }}
              rowClassName={setTableRowClassName}
              dataSource={dataSource}
              columns={getMaterialModalColumns(uploadForm)}
              rowKey={'keyID'}
              pagination={false}
            />
          </Form.Item>
        </Form>
      </div>
    );
  },
);
